/// <reference path="../../sage/sage.util.js" />

var GroundPainter = Base.extend({
    initialize: function initialize() {
        this.SECTION_LENGTH = 20.0;
        this.GROUND_COLOR_1 = "#22AA22",
        this.GROUND_COLOR_2 = "#55AA55";
    },
    paint: function paint(context) {
        var totalMovement = Math.round(context.camera.totalMovement);
        if (totalMovement < 0) totalMovement += this.SECTION_LENGTH * 1000000;
        var offset = totalMovement % (this.SECTION_LENGTH);
        if (offset > 0) offset = (this.SECTION_LENGTH) - offset;
        if (offset < 0) offset = Math.abs(this.SECTION_LENGTH);

        var lineLocation = context.viewPort.size.h,
			centerLocation = lineLocation / 2,
			prevLineLocation = lineLocation,
			stripeSize = 1,
			stripeIndex = 0,
			current = 0,
			c = context.camera.h + context.camera.z,
			distance = 1.0 + offset,
			d2v = context.viewPort.distanceToView;

        context.backLayer.strokeStyle = this.GROUND_COLOR_1;
        context.backLayer.fillStyle = this.GROUND_COLOR_1;
        context.backLayer.fillRect(0, centerLocation, context.viewPort.size.w, context.viewPort.size.h - centerLocation);

        context.backLayer.strokeStyle = this.GROUND_COLOR_2;
        context.backLayer.fillStyle = this.GROUND_COLOR_2;
        while (lineLocation > centerLocation) {
            prevLineLocation = lineLocation;

            current = c / distance * d2v;
            lineLocation = centerLocation + Math.round(current * context.viewPort.scale);

            if (lineLocation < centerLocation) continue;
            else if (lineLocation >= context.viewPort.size.h)
                lineLocation = context.viewPort.size.h;
            else {
                stripeSize = prevLineLocation - lineLocation;
                if (stripeSize == 0) break;
                if (stripeIndex % 2 == 1) {
                    context.backLayer.fillRect(0, lineLocation, context.viewPort.size.w, stripeSize);
                }
            }
            distance += (this.SECTION_LENGTH / 2);
            stripeIndex++;
        }
    }
});
